﻿using FieldTools.Client.Entity.OneBotManage;
using FieldTools.Client.Model.Window;
using FieldTools.Util;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FieldTools.Client.Business.API
{
    /// <summary>
    /// onebot api，仅实现部分
    /// </summary>
    public class OneBotApi
    {
        #region 请求方法
        /// <summary>
        /// post请求
        /// </summary>
        /// <param name="url">请求接口地址</param>
        /// <param name="postStr">请求字符串</param>
        /// <param name="headers">输出头</param>
        /// <param name="bodyType">body类型</param>
        /// <returns></returns>
        public static async Task<string> ExecutePostAsync(string url, string postStr, Dictionary<string, string> headers = null, string bodyType = "application/json")
        {
            try
            {
                using HttpClientHandler handler = new() { UseProxy = false, AllowAutoRedirect = false };
                using HttpClient httpClient = new(handler);
                httpClient.Timeout = TimeSpan.FromMinutes(5);

                using StringContent httpContent = new(postStr, Encoding.UTF8, bodyType);
                headers?.ForEach(aHeader =>
                {
                    httpContent.Headers.Add(aHeader.Key, aHeader.Value);
                });
                using var resultTask = await httpClient.PostAsync(url, httpContent);
                return await resultTask.Content.ReadAsStringAsync();
            }
            catch (Exception ex)
            {
                return "请求失败:" + ex.Message;
            }
        }

        /// <summary>
        /// 执行请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="parmUrl"></param>
        /// <param name="body"></param>
        /// <returns></returns>
        public static async Task<T?> ExecuteRequest<T>(string parmUrl, object body)
        {
            var config = CacheHelper.GetCache<MyQQModel>(nameof(MyQQModel));
            if (config == null) return default;
            var onebotConfig = config.OnebotConfig;
            if (onebotConfig != null)
            {
                Dictionary<string, string> headers = [];
                if (!string.IsNullOrEmpty(onebotConfig.Token)) headers.Add("Authorization", "Bearer " + onebotConfig.Token);
                var res = await ExecutePostAsync(onebotConfig.PostUrl.RemoveEndChar('/')+ parmUrl.RemoveStartChar('/') + "/" + parmUrl, body.ToJson(), headers);
                if (string.IsNullOrEmpty(res)) return default;
                try
                {
                    return res.ToObject<T>();
                }
                catch (Exception)
                {
                    return default;
                }
            }
            return default;
        }

        #endregion

        #region API
        /// <summary>
        /// 发送私聊信息
        /// </summary>
        /// <param name="info"></param>
        /// <returns>消息id</returns>
        public static async Task<string?> SendPrivateMsg(OneBotSendMessageInfo info)
        {
            ArgumentNullException.ThrowIfNull(info);
            var res = await ExecuteRequest<OneBotReturnInfo>("/send_private_msg", info);
            if(res==null || res.Retcode != 0) return string.Empty;
            return res.Data?.MessageId;
        }
        /// <summary>
        /// 发送群消息
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public static async Task<string?> SendGroupMsg(OneBotSendMessageInfo info)
        {
            ArgumentNullException.ThrowIfNull(info);
            var res = await ExecuteRequest<OneBotReturnInfo>("/send_group_msg", info);
            if (res == null || res.Retcode != 0) return string.Empty;
            return res.Data?.MessageId;
        }
        #endregion
    }
}
